package com.Earth01;
/*
*面试题 01.06. 字符串压缩 - 力扣（LeetCode）
* */
public class Earth240707 {
    public static void main(String[] args) {
        String S = "abbccd";
        String res = compressString(S);
        System.out.println(res);
    }
    public static String compressString(String S) {
        /*
        * 初始化快慢指针指向0
        * fast指针向右移动，当和slow指向的元素相同，该元素个数+1
        *                 当和slow指向的元素不同，将slow和个数拼接，然后将个数归1，移动slow指针到fast
        * */
        if(S.length()==0){
            return S;
        }
        int fast = 0,slow = 0;
        int count = 1;
        StringBuilder sb = new StringBuilder();
        char[] chStr = S.toCharArray();
        while(true){
            if(fast >= chStr.length-1 || slow >= chStr.length - 1){
                sb.append(chStr[slow]).append(count);
                break;
            }
            fast++;
            if(chStr[slow] == chStr[fast]){
                count++;
            }else {
                sb.append(chStr[slow]).append(count);
                count = 1;
                slow = fast;
            }
        }
        String newS = sb.toString();
        if(newS.length() >= S.length()){
            return S;
        }
        return newS;
    }
}
